//
//  ICSgement.swift
//  ICSegmentControl
//
//  Created by cuichengcheng on 2017/12/7.
//  Copyright © 2017年 cuichengcheng. All rights reserved.
//

import UIKit
class ICSgement: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    var didSelectClo:((_ index:Int)->())? = nil
    private var segCellId = "ic_segCellId"
    private let flowLayout = UICollectionViewFlowLayout()
    //选中字体颜色 及 底部线颜色
    var currentIndicatorTintColor:UIColor = RGB(0x333333) {
        didSet{
            segCV.reloadData()
        }
    }
    var segTitles:Array<String> = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    //是否显示分隔线 default false
    var showSeprateLine = false
    var seprateColor:UIColor = .lightGray
    var itemW:CGFloat = ic_scale_w(80)
    var currentSelectIndex = 0
    //是否显示选中线
    var showCurrentBottomLine = true
    lazy var segCV:UICollectionView = {
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        cv.showsVerticalScrollIndicator = false
        cv.showsHorizontalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = .clear
        cv.register(ICSegCell.classForCoder(), forCellWithReuseIdentifier: segCellId)
        self.addSubview(cv)
        return cv
    }()

    //分隔线高度比例 vs self
    var seprateRatio:CGFloat = 0.7 
    //自定义cell
    var customCellClass:AnyClass = ICSegCell.classForCoder() {
        didSet{
            segCellId = NSStringFromClass(customCellClass)
            segCV.register(customCellClass, forCellWithReuseIdentifier: segCellId)
        }
    }
    //自定义cell cell赋值  回调
    var customCellForIndexClo:((_ cell:UICollectionViewCell, _ index:Int) -> ())? = nil
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    init() {
        super.init(frame: .zero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        segCV.frame = self.bounds
        flowLayout.itemSize = CGSize(width: itemW, height: self.bounds.height)
        segCV.selectItem(at: IndexPath.init(item: currentSelectIndex, section: 0) , animated: false, scrollPosition: .centeredHorizontally)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return segTitles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: segCellId, for: indexPath)
        if cell.isKind(of: ICSegCell.classForCoder()) {
            let segCell = cell as! ICSegCell
            segCell.lab.text = segTitles[indexPath.item]
            segCell.bottomlayer.isHidden = !showCurrentBottomLine
            segCell.currentIndicatorTintColor = currentIndicatorTintColor
            segCell.rightlayer.backgroundColor = seprateColor.cgColor
            segCell.seprateRatio = seprateRatio
            segCell.rightlayer.isHidden = !showSeprateLine
            return segCell
        }else {
            if customCellForIndexClo != nil {
                customCellForIndexClo!(cell, indexPath.item)
            }
            return cell
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        currentSelectIndex = indexPath.item
        if didSelectClo != nil {
            didSelectClo!(indexPath.item)
        }
    }
    func currentSelect(_ index:Int, animated:Bool) {
        segCV.selectItem(at: IndexPath(item:index, section:0), animated: animated, scrollPosition: .centeredHorizontally)
    }
    
    deinit {
        print("释放---" + NSStringFromClass(self.classForCoder))
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
class ICSegCell: UICollectionViewCell {
    let lab = UILabel()
    let bottomlayer = CALayer()
    let rightlayer = CALayer()
    var currentIndicatorTintColor:UIColor = RGB(0x333333) {
        didSet{
            setSelected()
        }
    }
    //分隔线高度比例 vs self
    var seprateRatio:CGFloat = 0.0 {
        didSet{
            self.setNeedsLayout()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        lab.textAlignment = .center
        lab.font = getFont(ic_scale_w(15))
        lab.textColor = .gray
        self.contentView.addSubview(lab)
        lab.frame = self.bounds
        
        bottomlayer.backgroundColor = UIColor.clear.cgColor
        bottomlayer.frame = CGRect(x: 2, y: frame.maxY-1.5, width: frame.width-4, height: 1.5)
        self.layer.addSublayer(bottomlayer)
        
        rightlayer.backgroundColor = UIColor.lightGray.cgColor
        self.layer.addSublayer(rightlayer)
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        rightlayer.frame = CGRect(x: frame.width-1.5, y: frame.height*fabs(1-seprateRatio)/2, width: 1.5, height: frame.height*seprateRatio)
    }
    override var isSelected: Bool {
        didSet{
            setSelected()
        }
    }
    func setSelected() {
        bottomlayer.backgroundColor = isSelected ? currentIndicatorTintColor.cgColor : UIColor.clear.cgColor
        lab.textColor = isSelected ? currentIndicatorTintColor : .gray
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

